package com.example.sunmiv1.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.sunmiv1.BuildConfig;
import com.example.sunmiv1.R;
import com.example.sunmiv1.entity.LoginBean;
import com.example.sunmiv1.entity.LoginEntity;
import com.example.sunmiv1.entity.SigninBean;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.github.houbb.opencc4j.util.ZhTwConverterUtil;
import com.google.gson.Gson;
import com.google.gson.Strictness;
import com.google.gson.stream.JsonReader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.pay.PayCallback;
import org.pay.PayUtils;
import org.pay.model.PayRespData;
import org.pay.utils.StringUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import android.os.SystemProperties;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.StringReader;
import java.util.HashMap;

public class LoginActivity extends Activity {

    @BindView(R.id.login_acNum)
    EditText loginAcNum;
    @BindView(R.id.login_pass)
    EditText loginPass;
    @BindView(R.id.login_check)
    CheckBox loginCheck;
    @BindView(R.id.login_login_tv)
    TextView loginLoginTv;
    @BindView(R.id.login_business)
    RadioButton loginBusiness;
    @BindView(R.id.login_shopOwner)
    RadioButton loginShopOwner;
    @BindView(R.id.login_staff)
    RadioButton loginStaff;
    @BindView(R.id.login_realm_edit)
    EditText loginRealmEdit;
    @BindView(R.id.login_realm_testing)
    TextView loginRealmTesting;
    @BindView(R.id.login_realm_sure)
    TextView loginRealmSure;
    @BindView(R.id.login_realm)
    LinearLayout loginRealm;
    @BindView(R.id.login_logo)
    ImageView loginLogo;

    private Context context;
    private ACache aCache;
    private LoadingDialog loadingDialog;
    private LoginBean loginBean;//商家
    private SigninBean signinBean;//店長
    private LoginEntity loginEntity;//收銀員
    private Intent intent;
    private SharedPreferences sp;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    loadingDialog.dismiss();
                    aCache.put("uid", loginBean.getUserinfo().getUid());
                    aCache.put("userType", loginBean.getUserinfo().getUsertype() + "");
                    aCache.put("storeTag", loginBean.getUserinfo().getStoretag());
                    aCache.put("is_check_show_invenum", loginBean.getUserinfo().getIs_check_show_invenum());
                    if (loginBean.getUserinfo().getStorelist().size() > 0) {
                        aCache.put("storeid", loginBean.getUserinfo().getStorelist().get(0).getStoreid());
                    }
//                    JSONArray jsonArray = new JSONArray(loginBean.getUserinfo().getStorelist());
                    JSONArray jsonArray = new JSONArray();
                    for (int i = 0; i < loginBean.getUserinfo().getStorelist().size(); i++) {
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("name", loginBean.getUserinfo().getStorelist().get(i).getName());
                            jsonObject.put("storeid", loginBean.getUserinfo().getStorelist().get(i).getStoreid());
                            jsonArray.put(jsonObject);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    Gson gson=new Gson();
                    Log.d("店鋪列表1",gson.toJson(jsonArray));
                    aCache.put("storelist", jsonArray);
                    aCache.put("merchantid", loginBean.getUserinfo().getMerchantid());
                    aCache.put("login_acnum", loginAcNum.getText().toString());
                    if (loginCheck.isChecked()) {
                        aCache.put("login_pass", loginPass.getText().toString());
                        aCache.put("login_ischeck", "1");
                    } else {
                        aCache.put("login_pass", "");
                        aCache.put("login_ischeck", "0");
                    }
                    aCache.put("operator_id", loginBean.getUserinfo().getOperator_id());
                    aCache.put("credit", loginBean.getUserinfo().isIs_credit() ? "1" : "0");
                    aCache.put("platform_type",loginBean.getUserinfo().getPlatform_type());
                    Toast.makeText(context, loginBean.getMsg(), Toast.LENGTH_SHORT).show();
                    intent = new Intent(context, MainActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                case 2:
                    Toast.makeText(context, loginBean.getMsg(), Toast.LENGTH_SHORT).show();
                    loadingDialog.dismiss();
                    break;
                case 3:
                    loadingDialog.dismiss();
                    aCache.put("uid", signinBean.getUserinfo().getUid());
                    aCache.put("userType", signinBean.getUserinfo().getUsertype() + "");
                    aCache.put("storeTag", signinBean.getUserinfo().getStoretag());
                    aCache.put("storeid", signinBean.getUserinfo().getStoreid());
                    aCache.put("merchantid", signinBean.getUserinfo().getMerchantid());
                    aCache.put("is_check_show_invenum", signinBean.getUserinfo().getIs_check_show_invenum());
                    aCache.put("supplier_type", signinBean.getUserinfo().getSupplier_type());// 供貨商類型  1常規 2寄售
                    aCache.put("login_acnum", loginAcNum.getText().toString());
                    if (loginCheck.isChecked()) {
                        aCache.put("login_pass", loginPass.getText().toString());
                        aCache.put("login_ischeck", "1");
                    } else {
                        aCache.put("login_pass", "");
                        aCache.put("login_ischeck", "0");
                    }
                    aCache.put("operator_id", signinBean.getUserinfo().getOperator_id());
                    aCache.put("goods_integral_state", signinBean.getUserinfo().getGoods_integral_state());
                    aCache.put("credit", signinBean.getUserinfo().isIs_credit() ? "1" : "0");
                    aCache.put("platform_type",signinBean.getUserinfo().getPlatform_type());
                    Toast.makeText(context, signinBean.getMsg(), Toast.LENGTH_SHORT).show();
                    intent = new Intent(context, MainActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                case 4:
                    Toast.makeText(context, signinBean.getMsg(), Toast.LENGTH_SHORT).show();
                    loadingDialog.dismiss();
                    break;
                case 5:
                    loadingDialog.dismiss();
                    Toast.makeText(context, loginEntity.getMsg(), Toast.LENGTH_SHORT).show();
                    aCache.put("is_wifi", "1");
                    aCache.put("uid", loginEntity.getData().getCashier_id());
                    aCache.put("userType", "3");
                    aCache.put("storeTag", loginEntity.getData().getStore_name());
                    aCache.put("storeid", loginEntity.getData().getStore_id());
                    aCache.put("merchantid", loginEntity.getData().getMerchant_id());
                    aCache.put("login_acnum", loginAcNum.getText().toString());
                    aCache.put("supplier_type", loginEntity.getData().getSupplier_type());// 供貨商類型  1常規 2寄售
                    if (loginCheck.isChecked()) {
                        aCache.put("login_pass", loginPass.getText().toString());
                        aCache.put("login_ischeck", "1");
                    } else {
                        aCache.put("login_pass", "");
                        aCache.put("login_ischeck", "0");
                    }
                    aCache.put("login_key", loginEntity.getData().getLogin_key());
                    aCache.put("cashier_id", loginEntity.getData().getCashier_id());
                    aCache.put("name", loginEntity.getData().getName());
                    aCache.put("store_preferential", loginEntity.getData().getAuth().getStore_preferential() + "");
                    aCache.put("preferential", loginEntity.getData().getAuth().getPreferential() + "");
                    aCache.put("sales_diction", loginEntity.getData().getAuth().getSale_diction_state() + "");
                    aCache.put("flag", loginEntity.getData().getCash_model());
                    if (loginEntity.getData().getPrint_time() != null) {
                        aCache.put("print_time", loginEntity.getData().getPrint_time());
                    }

                    aCache.put("integral_arrive_cash", loginEntity.getData().getMerchantConfig().getIntegral_arrive_cash());
                    aCache.put("integral_arrive_cash_data", loginEntity.getData().getMerchantConfig().getIntegral_arrive_cash_data());
                    aCache.put("integral_arrive_cash_rate", loginEntity.getData().getMerchantConfig().getIntegral_arrive_cash_rate());
                    aCache.put("integral_arrive_cash_price", loginEntity.getData().getMerchantConfig().getIntegral_arrive_cash_price());

                    aCache.put("marketing_methods", loginEntity.getData().getMerchantConfig().getMarketing_methods());

                    aCache.put("manual_discount", loginEntity.getData().getAuth().getManual_discount() + "");//是否開啓單品打折
                    aCache.put("store_manual_discount", loginEntity.getData().getAuth().getStore_manual_discount() + "");//門店是否開啓折上折
                    aCache.put("manual_min_discount", loginEntity.getData().getAuth().getManual_min_discount() + "");//手動折扣最低折扣
                    aCache.put("manual_max_amount", loginEntity.getData().getAuth().getManual_max_amount() + "");//手動折扣最多優惠金額
                    aCache.put("is_check_show_invenum", loginEntity.getData().getAuth().getIs_check_show_invenum());
//                    aCache.put("code_auth", loginEntity.getData().getAuth().getCode_auth()+"");//是否需要授權碼 0=不需要 1=需要

                    // TODO: 2020/6/19 該版本暫時註釋收銀贈送商品
                    aCache.put("goods_gifts_auth", loginEntity.getData().getAuth().getGoods_gifts_auth() + "");
                    aCache.put("goods_gifts_num", loginEntity.getData().getAuth().getGoods_gifts_num() + "");

                    aCache.put("addGood", loginEntity.getData().getAuth().getAdd_goods_jurisdiction() + "");//1.開啓添加商品 2.未開啓添加商品
                    aCache.put("store_operation_vip", loginEntity.getData().getAuth().getStore_operation_vip() + "");
                    aCache.put("cash_model", loginEntity.getData().getCash_model());
                    aCache.put("other_pay", loginEntity.getData().getMerchantConfig().getOther_pay());
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("cashier_id", loginEntity.getData().getCashier_id());
                    editor.putString("store_id", loginEntity.getData().getStore_id());
                    editor.putString("merchant_id", loginEntity.getData().getMerchant_id());
                    aCache.put("credit", loginEntity.getData().isCredit() ? "1" : "0");
                    aCache.put("platform_type",loginEntity.getData().getPlatform_type());
                    editor.commit();
                    intent = new Intent(context, MainActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                case 6:
                    loadingDialog.dismiss();
                    Toast.makeText(context, loginEntity.getMsg(), Toast.LENGTH_SHORT).show();
                    break;
                case 7:
                    Toast.makeText(context, "連接服務器失敗\n請檢查網絡", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_login);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        sp = context.getSharedPreferences("context", Activity.MODE_PRIVATE);//創建sp對象
        ButterKnife.bind(this);
        startQrCode();
        loginAcNum.setText(aCache.getAsString("login_acnum"));

        if ("".equals(aCache.getAsString("login_pass")) || aCache.getAsString("login_pass") == null) {
        } else {
            loginPass.setText(aCache.getAsString("login_pass"));
        }
        if ("1".equals(aCache.getAsString("login_ischeck"))) {
            loginCheck.setChecked(true);
        } else {
            loginCheck.setChecked(false);
        }
        if (sp.getString("url", "") == null || TextUtils.isEmpty(sp.getString("url", ""))) {
            loginRealm.setVisibility(View.VISIBLE);
        }

        if ("1".equals(aCache.getAsString("userType"))) {
            loginBusiness.setChecked(true);
            loginShopOwner.setChecked(false);
            loginStaff.setChecked(false);
        } else if ("2".equals(aCache.getAsString("userType"))) {
            loginBusiness.setChecked(false);
            loginShopOwner.setChecked(true);
            loginStaff.setChecked(false);
        } else if ("3".equals(aCache.getAsString("userType"))) {
            loginBusiness.setChecked(false);
            loginShopOwner.setChecked(false);
            loginStaff.setChecked(true);
        }
        if(BuildConfig.DEBUG){
            loginAcNum.setText("18038077702");
            loginPass.setText("123456");
        }
    }


    // 開始掃碼
    private void startQrCode() {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申請權限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Constant.REQ_PERM_CAMERA);
            return;
        }
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申請權限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 123);
            return;
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申請權限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 二維碼掃碼
//        Intent intent = new Intent(context, CaptureActivity.class);
//        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (aCache.getAsString("logo") != null || !"".equals(aCache.getAsString("logo"))) {
            RequestOptions options = new RequestOptions();
            options.override(300, 300);
//            options.placeholder(R.mipmap.login_logo);//佔位圖  .error(R.mipmap.error_food)//如果是錯誤的情況
            Glide.with(context)
                    .load(aCache.getAsString("logo"))
                    .apply(options)
                    .into(loginLogo);
        }
    }

    private void getLogo() {
        HttpUtils.post(context, Common.GET_LOGO, new JSONObject(), new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                try {
                    JSONObject json = new JSONObject(text);
                    if (json.getInt("status") == 1) {
                        aCache.put("logo", json.getString("img"));
                        Log.e(TAG, "onSuccess: " + json.getString("img"));
                    } else {
                        aCache.put("logo", "");
                    }
                    RequestOptions options = new RequestOptions();
                    options.override(300, 300);
//            options.placeholder(R.mipmap.login_logo);//佔位圖  .error(R.mipmap.error_food)//如果是錯誤的情況
                    Glide.with(context)
                            .load(aCache.getAsString("logo"))
                            .apply(options)
                            .into(loginLogo);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 攝像頭權限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    startQrCode();
                } else {
                    // 被禁止授權
                    Toast.makeText(context, "請至權限中心打開本應用的文件讀寫權限", Toast.LENGTH_LONG).show();
                }
                break;
            case 123:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    startQrCode();
                } else {
                    // 被禁止授權
                    Toast.makeText(context, "請至權限中心打開本應用的文件讀寫權限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @OnClick({R.id.login_login_tv, R.id.login_realm, R.id.login_realm_testing, R.id.login_realm_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_realm:
                break;
            case R.id.login_realm_testing:
                if ("".equals(loginRealmEdit.getText().toString())) {
                    Toast.makeText(context, "請輸入域名", Toast.LENGTH_SHORT).show();
                    return;
                }
                testing(1);
                break;
            case R.id.login_realm_sure:
                if ("".equals(loginRealmEdit.getText().toString())) {
                    Toast.makeText(context, "請輸入域名", Toast.LENGTH_SHORT).show();
                    return;
                }
                aCache.put("url", loginRealmEdit.getText().toString());
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("url", loginRealmEdit.getText().toString());
                editor.commit();
                loginRealmEdit.setText("");
                loginRealm.setVisibility(View.GONE);
                getLogo();
//                testing(2);
                break;
            case R.id.login_login_tv:
                if ("".equals(loginAcNum.getText().toString())) {
                    Toast.makeText(context, "賬號不能爲空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if ("".equals(loginPass.getText().toString())) {
                    Toast.makeText(context, "密碼不能爲空", Toast.LENGTH_SHORT).show();
                    return;
                }
                toLogin();
                break;
        }
    }

    private void testing(final int type) {
        loadingDialog.show();
        Toast.makeText(context, "當前域名已被授權可以使用", Toast.LENGTH_SHORT).show();
        if (type == 2) {
            aCache.put("url", loginRealmEdit.getText().toString());
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("url", loginRealmEdit.getText().toString());
            editor.commit();
            loginRealmEdit.setText("");
            loginRealm.setVisibility(View.GONE);
            getLogo();
        }

//        JSONObject jsonObject = new JSONObject();
//        try {
//            jsonObject.put("site", loginRealmEdit.getText().toString());
//            jsonObject.put("appid", 4);
//            HttpUtils.post(context, "http://116.255.226.216:10022/index.php/VersionApi/Check/Checksite", jsonObject, new TextCallBack() {
//                @Override
//                protected void onSuccess(String text) {
//                    try {
//                        JSONObject json = new JSONObject(text);
//                        loadingDialog.dismiss();
//                        if (json.getInt("status") == 1) {
//
//                        } else {
//                            Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
//                        }
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }
//
//                @Override
//                protected void onFailure(ResponseException e) {
//                    loadingDialog.dismiss();
//                }
//            });
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }

    }

    private static final String TAG = "LoginActivity";


    private void toLogin() {
        loadingDialog.show();
        //PayUtils.test();
        String model = SystemProperties.get("ro.product.model");
        Build build=new Build();
        String auto_string = Tools.getCode();
        JSONObject jsonObject = new JSONObject();
        if(BuildConfig.DEBUG){
            Log.e(TAG, "toLogin: 登录");
        }
        try {
            jsonObject.put("username", loginAcNum.getText().toString());
            jsonObject.put("password", loginPass.getText().toString());
            String url = "";
            if (loginBusiness.isChecked()) {
                jsonObject.put("type", 3);
                url = Common.LOGIN;
            } else if (loginShopOwner.isChecked()) {
                jsonObject.put("type", 4);
                url = Common.LOGIN;
            } else {
                jsonObject.put("type", 5);
                jsonObject.put("equip", "Android " + model);
                jsonObject.put("auto_string", auto_string);
                url = Common.DO_LOGIN;
            }
            if(BuildConfig.DEBUG){
                Log.e(TAG, "toLogin: url="+url+" json="+jsonObject.toString());
            }
            HttpUtils.post(context, url, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    if (loginBusiness.isChecked()) {//商家
                        loginBean = GsonUtils.JsonToBean(text, LoginBean.class);
                        Message msg = new Message();
                        if (loginBean.getStatus() == 1) {
                            msg.what = 1;
                        } else {
                            msg.what = 2;
                        }
                        handler.sendMessage(msg);
                    } else if (loginShopOwner.isChecked()) {//店長登錄
                        signinBean = GsonUtils.JsonToBean(text, SigninBean.class);
                        Message msg = new Message();
                        if (signinBean.getStatus() == 1) {
                            msg.what = 3;
                        } else {
                            msg.what = 4;
                        }
                        handler.sendMessage(msg);
                    } else {//員工登錄
                        aCache.put("loginInfo", text);
                        loginEntity = GsonUtils.JsonToBean(text, LoginEntity.class);
                        Message msg = new Message();
                        if (loginEntity.getStatus() == 1) {
                            msg.what = 5;
                        } else {
                            msg.what = 6;
                        }
                        handler.sendMessage(msg);
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    Log.e(TAG, "onFailure: " + e.getMessage());
                    loadingDialog.dismiss();
                    handler.sendEmptyMessage(7);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
            if(BuildConfig.DEBUG){
                Log.e(TAG, "toLogin: error "+e);
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否則所有的組件都不會有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);

    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //獲取輸入框當前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 點擊的是輸入框區域，保留點擊EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
